<template>
    <div class="pdf-view">
        <div class="pdf-view-header">
            <el-button-group>
                <el-button @click="prevPage" icon="ArrowLeft"></el-button>
                <el-button>{{ $t('pdf_view.btn_text_1') }}{{ currentPage }}{{ $t('pdf_view.btn_text_2') }}·{{ $t('pdf_view.btn_text_3') }}{{ pageCount }}{{ $t('pdf_view.btn_text_4') }}</el-button>
                <el-button @click="nextPage" icon="ArrowRight"></el-button>
            </el-button-group>
        </div>
        <div class="pdf-view-content">
            <canvas ref="pdfCanvas" v-loading="loading"></canvas>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'

import { useI18n } from 'vue-i18n'
import type { SupportedLocales } from '@/locales/i18n'
import type { MessageSchema } from '@/types/i18n'

import * as pdfjsLib from 'pdfjs-dist'
import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.min.mjs?url'
pdfjsLib.GlobalWorkerOptions.workerSrc = pdfjsWorker

// import pdfUrl from '@/assets/pdf/关于此次参考的总结.pdf?url'

const props = defineProps<{
    fileUrl: string
}>()
const loading = ref(false);
const pdfCanvas = ref<HTMLCanvasElement>()
const currentPage = ref(1)
const pageCount = ref(0)
let pdfDoc: pdfjsLib.PDFDocumentProxy | null = null
const { t } = useI18n<{ message: MessageSchema }, SupportedLocales>()

const loadPDF = async (url: string) => {
    try {
        // 先获取文件内容进行检查
        loading.value = true;
        console.log("我是url：", url);
        const response = await fetch(url)
        const buffer = await response.arrayBuffer()

        // 检查文件头是否是PDF格式（%PDF）
        const header = new Uint8Array(buffer.slice(0, 4))
        const headerStr = String.fromCharCode(...header)

        if (headerStr !== '%PDF') {
            console.error(t('pdf_view.err_msg_1'), headerStr)
            return
        }

        const loadingTask = pdfjsLib.getDocument(buffer)
        pdfDoc = await loadingTask.promise
        pageCount.value = pdfDoc.numPages
        renderPage(currentPage.value)
        loading.value = false;
    } catch (err) {
        console.error(t('pdf_view.err_msg_2'), err)
    }
}
const renderPage = async (num: number) => {
    if (!pdfDoc || !pdfCanvas.value) return

    const page = await pdfDoc.getPage(num)
    const viewport = page.getViewport({ scale: 1.5 })
    const canvas = pdfCanvas.value
    const context = canvas.getContext('2d')

    canvas.height = viewport.height
    canvas.width = viewport.width

    await page.render({
        canvasContext: context!,
        viewport: viewport,
    }).promise
}

const nextPage = () => {
    if (currentPage.value < pageCount.value) {
        currentPage.value++
        renderPage(currentPage.value)
    }
}

const prevPage = () => {
    if (currentPage.value > 1) {
        currentPage.value--
        renderPage(currentPage.value)
    }
}

onMounted(() => {
    loadPDF(props.fileUrl)
    // loadPDF(pdfUrl)
})
</script>

<style scoped lang="less">
.pdf-view {
    width: 100%;
    height: 100%;

    display: flex;
    flex-direction: column;

    .pdf-view-header {
        display: flex;
        align-items: center;
        gap: 10px;
        flex-shrink: 0;

        border-bottom: 1px solid #ccc;
        padding: 20px;
        background-color: #ebebeb;

        .el-button-group {
            background-color: #fff;

            .el-button {
                color: #999999;
                font-size: 16px;

                &:hover {
                    border-color: #f0642359;
                    color: #f06423;
                    background-color: #f0642305;
                }
            }
        }
    }

    .pdf-view-content {
        width: 100%;
        flex-grow: 1;
        overflow-x: hidden;
        overflow-y: auto;
        background-color: #f4f4f4;

        canvas {
            margin: 0 auto;
            box-shadow:
                inset 0 1px 0 rgba(255, 255, 255, 0.2),
                0 1px 20px rgba(0, 0, 0, 0.2);
            display: block;
            width: 100%;
        }
    }
}
</style>
